#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: close.sh
# Description: 
#   
# Edit History: 
#   2011-02-23    File created.
#========================================================================
# pipe(|) to report, it will execute report as command
ps | awk '{ report = "cat -n"
print "Awk script failed:", $0 | report
print "at record number", FNR, "of", FILENAME  | report
close(report)
}'

ps | awk '{
print $1 | "sort -r > names.sorted"
close("sort -r > names.sorted")
}'

# Reasons why you might need to close an output file:
# 1.To write a file and read it back later on in the same awk program. 
#   Close the file when you are finished writing it; then you can start reading it with getline (see section Explicit Input with getline).
# 2.To write numerous files, successively, in the same awk program. 
#   If you don't close the files, eventually you may exceed a system limit on the number of open files in one process. 
#   So close each one when you are finished writing it.
# 3.To make a command finish. When you redirect output through a pipe, 
#   the command reading the pipe normally continues to try to read input as long as the pipe is open. 
#   Often this means the command cannot really do its work until the pipe is closed. 
#   For example, if you redirect output to the mail program, the message is not actually sent until the pipe is closed.
# 4.To run the same program a second time, with the same arguments. 
#   This is not the same thing as giving more input to the first run! 
#   For example, suppose you pipe output to the mail program. 
#   If you output several lines redirected to this pipe without closing it, 
#   they make a single message of several lines. 
#   By contrast, if you close the pipe after each line of output, then each line makes a separate message.

# close returns a value of zero if the close succeeded. Otherwise, the value will be non-zero.
